package cn.wolfcode.crm.web.controller;

import cn.wolfcode.crm.domain.Permission;
import cn.wolfcode.crm.domain.Role;
import cn.wolfcode.crm.query.QueryObject;
import cn.wolfcode.crm.service.IPermissionService;
import cn.wolfcode.crm.service.IRoleService;
import cn.wolfcode.crm.util.JsonResult;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.List;

@Controller
@RequestMapping("/role")
public class RoleController {

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;

    // 提供一个方法处理查询所有部门数据请求，响应 HTML
    @RequestMapping("/list")
    @RequiresPermissions(value = {"role:list", "角色列表"}, logical = Logical.OR)
    public String list(Model model, QueryObject queryObject) {
        model.addAttribute("result", roleService.list(queryObject));
        return "role/list"; // /WEB-INF/views/role/list.jsp
    }

    @RequestMapping("/input")
    @RequiresPermissions(value = {"role:input", "角色编辑"}, logical = Logical.OR)
    public String input(Long id, Model model) {
        List<Permission> permissions = permissionService.listAll();
        model.addAttribute("permissions", permissions);
        if (id != null) { // 点击了修改按钮过来  编辑
            Role role = roleService.get(id);
            model.addAttribute("role", role);
        }
        return "role/input"; // /WEB-INF/views/role/input.jsp
    }

    @RequestMapping("/saveOrUpdate")
    @RequiresPermissions(value = {"role:saveOrUpdate", "角色保存/更新"}, logical = Logical.OR)
    public String saveOrUpdate(Role role, Long[] ids) {
        if (role.getId() == null) { // 代表新增
            roleService.save(role, ids);
        } else { // 代表修改
            roleService.update(role, ids);
        }
        return "forward:/role/list.do";  // http://localhost/role/list.do
    }

    @RequestMapping("/delete")
    @ResponseBody
    @RequiresPermissions(value = {"role:delete", "角色删除"}, logical = Logical.OR)
    public JsonResult delete(Long id) {
        roleService.delete(id);
        return new JsonResult();
    }
}
